package edu.dayu.config;

import edu.dayu.util.ClubException;
import edu.dayu.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                if ("OPTIONS".equals(request.getMethod())){
                    return true;
                }
                String accessToken = (String)redisTemplate.opsForValue().get("token");
                String accessToken1 = request.getHeader("token");
                if (accessToken != null && accessToken.equals(accessToken1)){
                    return true;
                }else{
                    throw new ClubException(ResultCodeEnum.TOKEN_ERROR);
                }
            }
        }).addPathPatterns("/admin/**");
    }
}
